import React, { useState, useEffect } from 'react';
import { Card, Descriptions, Button } from 'antd';
import { useLocation, useNavigate } from 'react-router-dom';
import { createStyles } from 'antd-style';
import CustomPageContainer from '@/components/CustomPageContainer';
import { deptpage } from '@/services/system/departmentmanage';
import { useModel } from '@umijs/max';

interface DeptTreeItem {
  id: number;
  departmentId: string;
  deptName: string;
  parementId: string | null;
  children?: DeptTreeItem[];
}

const useStyles = createStyles(({ token }) => ({
  container: {
    padding: '24px',
    background: '#f5f5f5',
    minHeight: 'calc(100vh - 48px)',
  },
  card: {
    borderRadius: '8px',
    boxShadow: '0 2px 8px rgba(0, 0, 0, 0.15)',
  },
  contentContainer: {
    maxWidth: '800px',
    margin: '0 auto',
    padding: '24px',
  },
  title: {
    fontSize: '16px',
    fontWeight: 'bold',
    color: '#1890ff',
    borderBottom: '2px solid #1890ff',
    paddingBottom: '8px',
    marginBottom: '24px',
  },
  descriptions: {
    marginTop: '24px',
    '& .ant-descriptions-item-label': {
      fontWeight: 500,
      color: '#333',
      width: '120px',
      backgroundColor: '#fafafa',
    },
    '& .ant-descriptions-item-content': {
      color: '#666',
    },
  },
  buttonGroup: {
    display: 'flex',
    justifyContent: 'center',
    gap: '16px',
    marginTop: '32px',
  },
  button: {
    width: '120px',
    height: '36px',
    borderRadius: '4px',
    fontSize: '14px',
  },
}));

const DepartmentView: React.FC = () => {
  const { styles } = useStyles();
  const location = useLocation();
  const navigate = useNavigate();
  const record = location.state?.record || {};
  const [parentDeptName, setParentDeptName] = useState<string>('');
  const { institutionId, institutionRoleId } = useModel('auth');

  const formatDepartmentType = (type: number) => {
    return type === 1 ? '部门' : '其他';
  };

  // 查找上级部门名称
  const findParentDeptName = (deptList: DeptTreeItem[], targetId: string): string => {
    for (const dept of deptList) {
      if (dept.departmentId === targetId) {
        return dept.deptName;
      }
      if (dept.children) {
        const found = findParentDeptName(dept.children, targetId);
        if (found) return found;
      }
    }
    return '';
  };

  useEffect(() => {
    const fetchDeptTree = async () => {
      try {
        const res = await deptpage({
          institutionId: institutionId,
          institutionRoleId: institutionRoleId,
        });
        if (res.code === 200 && res.success) {
          if (record.parementId) {
            const parentName = findParentDeptName(res.data, record.parementId);
            setParentDeptName(parentName || '未知部门');
          }
      }
    } catch (error) {
        console.error('获取部门树失败:', error);
      }
    };

    if (record.parementId) {
      fetchDeptTree();
    }
  }, [record.parementId, institutionId, institutionRoleId]);

  return (
    <CustomPageContainer>
      <div className={styles.container}>
        <Card className={styles.card}>
          <div className={styles.contentContainer}>
            <div className={styles.title}>部门详情</div>
            <Descriptions
              bordered
              column={1}
              className={styles.descriptions}
              size="middle"
            >
              <Descriptions.Item label="部门名称">{record.deptName}</Descriptions.Item>
              <Descriptions.Item label="部门类型">{formatDepartmentType(record.deptCategory)}</Descriptions.Item>
              <Descriptions.Item label="上级部门">
                {record.parementId ? parentDeptName : '顶级'}
              </Descriptions.Item>
              <Descriptions.Item label="部门排序">{record.sort}</Descriptions.Item>
              <Descriptions.Item label="部门备注">{record.remark || '暂无备注'}</Descriptions.Item>
            </Descriptions>
            <div className={styles.buttonGroup}>
              <Button
                className={styles.button}
                onClick={() => navigate('/system/departmentmanage')}
              >
              返回
            </Button>
            </div>
          </div>
        </Card>
      </div>
    </CustomPageContainer>
  );
};

export default DepartmentView;
